package org.kl.bpm.service.conf;

import java.util.List;
import java.util.Map;

import org.kl.bf.utils.CRUDUtils;
import org.kl.bpm.entity.conf.BpmFormTemplate;
import org.kl.bpm.repository.conf.BpmFormTemplateDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

/**
 * 
 * @Author hqm
 * @CreateTime 2014年5月25日 下午8:40:29
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class BpmFormTemplateService {

	private BpmFormTemplateDao bpmFormTemplateDao;

	public BpmFormTemplate getBpmFormTemplate(String id) {
		return bpmFormTemplateDao.findOne(id);
	}

	public BpmFormTemplate find(String id) {
		return bpmFormTemplateDao.find(BpmFormTemplate.class, id);
	}

	public void saveBpmFormTemplate(BpmFormTemplate entity) {
		bpmFormTemplateDao.save(entity);
	}

	public void deleteBpmFormTemplate(String id) {
		bpmFormTemplateDao.delete(id);
	}

	public List<BpmFormTemplate> getAllBpmFormTemplate() {
		return bpmFormTemplateDao.findAll(new Sort(Direction.ASC, "name"));
	}

	public Page<BpmFormTemplate> getUserBpmFormTemplate(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType,
			String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<BpmFormTemplate> spec = buildSpecification(searchParams);

		return bpmFormTemplateDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<BpmFormTemplate> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<BpmFormTemplate> spec = DynamicSpecifications.bySearchFilter(filters.values(), BpmFormTemplate.class);
		return spec;
	}

	@Autowired
	public void setBpmFormTemplateDao(BpmFormTemplateDao bpmFormTemplateDao) {
		this.bpmFormTemplateDao = bpmFormTemplateDao;
	}

}
